<template>
  <div class="app-container">
    <div class="page-header">
      <h2>左侧菜单管理</h2>
      <p>iOS应用左侧菜单配置管理</p>
    </div>

    <div class="content-area">
      <el-card>
        <div slot="header" class="card-header">
          <span>菜单配置</span>
          <el-button type="primary" size="small" @click="handleAdd">
            <i class="el-icon-plus" /> 添加菜单
          </el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="menuList"
          style="width: 100%"
          row-key="id"
          @sort-change="handleSortChange"
        >
          <el-table-column prop="order" label="排序" width="80" sortable="custom">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.order"
                size="mini"
                :min="0"
                @change="handleOrderChange(scope.row)"
              />
            </template>
          </el-table-column>

          <el-table-column prop="icon" label="图标" width="80">
            <template slot-scope="scope">
              <div class="icon-preview" @click="handleIconEdit(scope.row)">
                <img v-if="scope.row.icon" :src="scope.row.icon" alt="icon">
                <i v-else class="el-icon-picture-outline" />
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="title" label="菜单名称" min-width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.title"
                size="mini"
                @blur="handleUpdate(scope.row)"
              />
            </template>
          </el-table-column>

          <el-table-column prop="route" label="路由" min-width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.route"
                size="mini"
                placeholder="请输入路由"
                @blur="handleUpdate(scope.row)"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 图标编辑对话框 -->
    <el-dialog title="编辑图标" :visible.sync="iconDialogVisible" width="500px">
      <div class="icon-edit-container">
        <div class="current-icon">
          <span>当前图标：</span>
          <img v-if="currentEditItem.icon" :src="currentEditItem.icon" alt="current icon">
          <span v-else>未设置</span>
        </div>

        <div class="icon-upload">
          <el-upload
            class="icon-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleIconUpload"
            :on-error="handleIconUploadError"
            :before-upload="beforeIconUpload"
            name="image"
            accept="image/*"
          >
            <img v-if="currentEditItem.icon" :src="currentEditItem.icon" class="icon-image">
            <i v-else class="el-icon-plus icon-uploader-icon" />
          </el-upload>
          <div class="upload-tip">点击上传图标 (建议尺寸: 50x50px)</div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="iconDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleIconSave">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAppleMenuList, saveAppleMenu, deleteAppleMenu } from '@/api/iosManagement'

export default {
  name: 'SideMenu',
  data() {
    return {
      loading: false,
      menuList: [],
      iconDialogVisible: false,
      currentEditItem: {},
      uploadUrl: process.env.VUE_APP_BASE_API + '/image/ossUpload'
    }
  },
  created() {
    this.loadMenuList()
  },
  methods: {
    // 加载左侧菜单列表
    async loadMenuList() {
      try {
        this.loading = true
        const response = await getAppleMenuList(1) // type=1 表示左侧菜单
        if (response && response.code === 1) {
          this.menuList = response.data || []
        } else {
          this.$message.error(response?.message || '加载失败')
          // 如果API失败，使用默认数据
          this.menuList = [
            {
              id: 1,
              title: '我的列表',
              icon: '',
              color: '',
              font_color: '#333333',
              route: '/my-list',
              order: 0,
              type: 1,
              status: '1'
            }
          ]
        }
      } catch (error) {
        console.error('加载左侧菜单列表失败:', error)
        this.$message.error('加载失败，使用默认数据')
        // 使用默认数据
        this.menuList = [
          {
            id: 1,
            title: '我的列表',
            icon: '',
            color: '',
            font_color: '#333333',
            route: '/my-list',
            order: 0,
            type: 1,
            status: '1'
          }
        ]
      } finally {
        this.loading = false
      }
    },

    // 添加菜单
    async handleAdd() {
      try {
        const newMenu = {
          title: '新菜单',
          icon: '',
          color: '',
          font_color: '#333333',
          route: '',
          order: this.menuList.length,
          type: 1,
          status: '1'
        }

        const response = await saveAppleMenu(newMenu)
        if (response.code === 1) {
          this.$message.success('添加成功')
          this.loadMenuList() // 重新加载列表
        } else {
          this.$message.error(response.message || '添加失败')
        }
      } catch (error) {
        console.error('添加菜单失败:', error)
        this.$message.error('添加失败')
      }
    },

    // 更新菜单
    async handleUpdate(row) {
      try {
        // 确保传递完整的默认参数
        const updateData = {
          title: row.title || '',
          icon: row.icon || '',
          color: row.color || '',
          font_color: row.font_color || '#333333',
          route: row.route || '',
          order: row.order || 0,
          type: 1,
          status: row.status || '1',
          id: row.id
        }

        const response = await saveAppleMenu(updateData)
        if (response.code === 1) {
          this.$message.success('更新成功')
        } else {
          this.$message.error(response.message || '更新失败')
        }
      } catch (error) {
        console.error('更新菜单失败:', error)
        this.$message.error('更新失败')
      }
    },

    // 删除菜单
    handleDelete(row) {
      this.$confirm('确定要删除这个菜单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const response = await deleteAppleMenu({ id: row.id })
          if (response.code === 1) {
            this.$message.success('删除成功')
            this.loadMenuList() // 重新加载列表
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除菜单失败:', error)
          this.$message.error('删除失败')
        }
      })
    },

    // 排序变化
    handleSortChange({ column, prop, order }) {
      console.log('排序变化:', { column, prop, order })
      // 前端排序，如果需要后端排序可以调用API
    },

    // 排序值变化
    async handleOrderChange(row) {
      try {
        const response = await saveAppleMenu({
          id: row.id,
          order: row.order,
          type: 1
        })
        if (response.code === 1) {
          this.$message.success('排序更新成功')
        } else {
          this.$message.error(response.message || '排序更新失败')
        }
      } catch (error) {
        console.error('更新排序失败:', error)
        this.$message.error('排序更新失败')
      }
    },

    // 编辑图标
    handleIconEdit(row) {
      this.currentEditItem = { ...row }
      this.iconDialogVisible = true
    },

    // 图标上传前验证
    beforeIconUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },

    // 图标上传成功
    handleIconUpload(response, file) {
      console.log('上传响应:', response)
      if (response.code === 1) {
        this.currentEditItem.icon = response.data.url
        this.$message.success('图标上传成功')
      } else {
        this.$message.error(response.message || '图标上传失败')
      }
    },

    // 图标上传失败
    handleIconUploadError(error, file, fileList) {
      console.error('上传失败:', error)
      this.$message.error('图标上传失败，请重试')
    },

    // 保存图标
    async handleIconSave() {
      try {
        // 确保传递完整的默认参数
        const updateData = {
          title: this.currentEditItem.title || '',
          icon: this.currentEditItem.icon || '',
          color: this.currentEditItem.color || '',
          font_color: this.currentEditItem.font_color || '#333333',
          route: this.currentEditItem.route || '',
          order: this.currentEditItem.order || 0,
          type: 1,
          status: this.currentEditItem.status || '1',
          id: this.currentEditItem.id
        }

        const response = await saveAppleMenu(updateData)
        if (response.code === 1) {
          this.$message.success('图标保存成功')
          this.loadMenuList() // 重新加载列表
        } else {
          this.$message.error(response.message || '图标保存失败')
        }
      } catch (error) {
        console.error('保存图标失败:', error)
        this.$message.error('图标保存失败')
      } finally {
        this.iconDialogVisible = false
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.content-area {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.icon-preview {
  width: 40px;
  height: 40px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.icon-preview:hover {
  border-color: #409eff;
}

.icon-preview img {
  width: 30px;
  height: 30px;
  object-fit: cover;
}

.icon-edit-container {
  text-align: center;
}

.current-icon {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.current-icon img {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.icon-uploader {
  display: inline-block;
}

.icon-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.icon-uploader .el-upload:hover {
  border-color: #409eff;
}

.icon-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.icon-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  display: block;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

.crop-section {
  margin-top: 15px;
  text-align: center;
}

.color-input-group {
  display: flex;
  align-items: center;
  gap: 5px;
}

.color-input-group .el-input {
  flex: 1;
}
</style>
